import { _decorator, BoxCollider2D, Component, Contact2DType, ERigidBody2DType, EventTouch, find, instantiate, Label, labelAssembler, Node, ParticleSystem2D, Prefab, ProgressBar, resources, RigidBody2D, Sprite, SpriteFrame, sys, Tween, tween, UIOpacity, UITransform, v2, v3 } from 'cc';
import { randomNum } from './utils';
import { AudioMgr } from './AudioMgr';
import { Fruit } from './Fruit';
import { Adsdk } from './Adsdk';
import { Dictionary } from './Dictionary';
const { ccclass, property } = _decorator;

@ccclass('gameMgr')
export class gameMgr extends Component {

    @property(Node)
    fruitRoot: Node;
    gameScoreLabel: Label;
    winPanel:Node;
    failPanel:Node;
    settingPanel:Node;
    yinxiaoBtn:Node;
    yinyueBtn:Node;
    zhendongBtn:Node;
    gateLevelLabel:Label;
    levelProBar:ProgressBar
    propRoot:Node
    dieLineRoot:Node;
    @property(Prefab)
    tipNodePre:Prefab;
    tipRoot:Node;
    canvasMask:Node;
    fruitBg0:Node;
    fruitBg1:Node;
    fruitBg2:Node;
    @property(Node)
    ground:Node;
    hammerTipStr:Node;

    gameWinToSeeAdvGetPropType=0;
    existFruit: Node = null;
    isNeedCompound = -1;
    isNeedCompoundPos = null;
    isPowerHammerIng = false;//是否现在正在进行大力锤
    isCommonBallIng = false;//是否现在正在进行万能球
    isGroundVibrationIng = false;//是否正在震动

    maxFruit = 14;//最大的水果

    isYinXiao = true;
    isYinYue = true;
    isZhenDong = true;
    isCanTouch = true;
    isPause = false;


    gateLevel = 1;
    private hasCommonBallNum;
    get HasCommonBallNum() {
        return this.hasCommonBallNum;
    }
    set HasCommonBallNum(value) {
        // this.hasCommonBallNum = value;
        // this.propRoot.getChildByName("commonBallPropBtn").getChildByName("value").getComponent(Label).string =value+"";
        // localStorage.setItem("hasCommonBallNum",JSON.stringify(value));

        // if(value<=0){
        //     this.propRoot.getChildByName("commonBallPropBtn").getChildByName("value").active=false;
        //     this.propRoot.getChildByName("commonBallPropBtn").getChildByName("vd").active=true;
        // }
        // else{
        //     this.propRoot.getChildByName("commonBallPropBtn").getChildByName("value").active=true;
        //     this.propRoot.getChildByName("commonBallPropBtn").getChildByName("vd").active=false;
        // }
    }
    private hasPowerHammerNum;
    get HasPowerHammerNum() {
        return this.hasPowerHammerNum;
    }
    set HasPowerHammerNum(value) {
        this.hasPowerHammerNum = value;
        this.propRoot.getChildByName("powerHammerPropBtn").getChildByName("value").getComponent(Label).string =value+"";
        localStorage.setItem("hasPowerHammerNum",JSON.stringify(value));
        if(value<=0){
            this.propRoot.getChildByName("powerHammerPropBtn").getChildByName("value").active=false;
            this.propRoot.getChildByName("powerHammerPropBtn").getChildByName("vd").active=true;
        }
        else{
            this.propRoot.getChildByName("powerHammerPropBtn").getChildByName("value").active=true;
            this.propRoot.getChildByName("powerHammerPropBtn").getChildByName("vd").active=false;
        }
    }

    private hasGroundVibrationPropNum;
    get HasGroundVibrationPropNum() {
        return this.hasGroundVibrationPropNum;
    }
    set HasGroundVibrationPropNum(value) {
        this.hasGroundVibrationPropNum = value;
        this.propRoot.getChildByName("shackPropBtn").getChildByName("value").getComponent(Label).string =value+"";
        localStorage.setItem("hasGroundVibrationPropNum",JSON.stringify(value));
        if(value<=0){
            this.propRoot.getChildByName("shackPropBtn").getChildByName("value").active=false;
            this.propRoot.getChildByName("shackPropBtn").getChildByName("vd").active=true;
        }
        else{
            this.propRoot.getChildByName("shackPropBtn").getChildByName("value").active=true;
            this.propRoot.getChildByName("shackPropBtn").getChildByName("vd").active=false;
        }
    }
    
    get compoundTotalNumGoNextLevel(){
        return 8+this.gateLevel*2;
    }

    private currCompoundNum = 0;
    set CurrCompoundNum(value) {
        this.currCompoundNum = value;
        localStorage.setItem("currCompoundNum",JSON.stringify(this.currCompoundNum));
        if (this.currCompoundNum >= this.compoundTotalNumGoNextLevel) {//下一关
            this.gameWin();
        }
        this.levelProBar.progress =this.currCompoundNum/this.compoundTotalNumGoNextLevel;
    }
    get CurrCompoundNum() {
        return this.currCompoundNum;
    }

    static ins: gameMgr = null;
    protected onLoad(): void {
        gameMgr.ins=this;
        this.gameScoreLabel=find("Canvas/UI/scoreRoot/scoreLabel").getComponent(Label);
        this.winPanel=find("Canvas/UI/popPanelRoot/winPanel");
        this.settingPanel=find("Canvas/UI/popPanelRoot/settingPanel");
        this.gateLevelLabel=find("Canvas/UI/gateRoot/leftLabel").getComponent(Label);
        this.levelProBar=find("Canvas/UI/gateRoot/ProgressBar").getComponent(ProgressBar);
        this.propRoot=find("Canvas/UI/propRoot");
        this.dieLineRoot=find("Canvas/bg/dieLineRoot");
        this.tipRoot=find("Canvas/UI/tipRoot");
        this.failPanel=find("Canvas/UI/popPanelRoot/failPanel");
        this.canvasMask=find("Canvas/canvasMask");
        this.fruitBg0=find("Canvas/bg/fruitBg0");
        this.fruitBg1=find("Canvas/bg/fruitBg1");
        this.fruitBg2=find("Canvas/bg/fruitBg2");
        this.hammerTipStr=find("Canvas/UI/hammerTipStr");

        this.yinxiaoBtn=find("Canvas/UI/popPanelRoot/settingPanel/yinxiaoBtn");
        this.yinyueBtn=find("Canvas/UI/popPanelRoot/settingPanel/yinyueBtn");
        this.zhendongBtn=find("Canvas/UI/popPanelRoot/settingPanel/zhendongBtn");

        if(localStorage.getItem("isYinXiao")){
            this.isYinXiao = JSON.parse(localStorage.getItem("isYinXiao"));
        }

        if(localStorage.getItem("isYinYue")){
            this.isYinYue = JSON.parse(localStorage.getItem("isYinYue"));
        }

        if(this.isYinYue){
            AudioMgr.ins.play("audio/bgm",1);
        }else{
            AudioMgr.ins.stop();
        }


        if(localStorage.getItem("isZhenDong")){
            this.isZhenDong = JSON.parse(localStorage.getItem("isZhenDong"));
        }
        this.setYxZd()
    }

    private gameScore;
    get GameScore(){
        return this.gameScore;
    }
    set GameScore(value){
        this.gameScore=value;
        this.gameScoreLabel.string="得分:"+value;
        localStorage.setItem("gameScore",value);
    }

    start() {
        Adsdk.instance.hideGridAdLeftOne()
        Adsdk.instance.hideGridAdRightOne()
        Adsdk.instance.showGridAdLeftOne()
        Adsdk.instance.showGridAdRightOne()
        Adsdk.instance.showInterstitialAd()
        //获取缓存
        if (localStorage.getItem("gateLevel")) {
            this.gateLevel = JSON.parse(localStorage.getItem("gateLevel"));
            console.log("cs1")
            // this.HasCommonBallNum = JSON.parse(localStorage.getItem("hasCommonBallNum"));
            console.log("cs2")

            this.HasPowerHammerNum = JSON.parse(localStorage.getItem("hasPowerHammerNum"));
            console.log("cs3")

            this.HasGroundVibrationPropNum = JSON.parse(localStorage.getItem("hasGroundVibrationPropNum"));
            console.log("cs4")

            this.GameScore = JSON.parse(localStorage.getItem("gameScore"));
            console.log("cs5")

            this.CurrCompoundNum=JSON.parse(localStorage.getItem("currCompoundNum"))
            console.log("cs6")


            //水果摆放缓存
            if (localStorage.getItem("fruitsData")) {
            console.log("cs7")

                let fruits=JSON.parse(localStorage.getItem("fruitsData"));//[x,y,angle,fruitsType]
                let createNum=0;
                for (let i = 0; i < fruits._typeKeyList.length; i++) {
                    resources.load(`prefab/fruits/fruit${fruits._typeValueList[i][3]}`, Prefab, (err, res) => {
                        let pre = instantiate(res);
                        pre.setParent(this.fruitRoot);
                        pre.setPosition(fruits._typeValueList[i][0], fruits._typeValueList[i][1], 0);
                        pre.angle=fruits._typeValueList[i][2]
                        pre.getComponent(Fruit).init(fruits._typeValueList[i][3]);
                        createNum+=1;
    
                        if (createNum==fruits._typeKeyList.length) {
                            for (let t = 0; t < this.fruitRoot.children.length; t++) {
                                if (this.fruitRoot.children[t]==this.existFruit) {
                                    continue;
                                }
                                console.log("改动态")
                                this.fruitRoot.children[t].getComponent(RigidBody2D).type = ERigidBody2DType.Dynamic
                            }
                        }
                    })
                }
            }
           
        }

        else {
            // this.HasCommonBallNum = 1;
            this.HasPowerHammerNum = 1;
            this.HasGroundVibrationPropNum = 1;
            this.GameScore=0;
            this.CurrCompoundNum=0;
            localStorage.setItem("gateLevel",JSON.stringify(1));

        }

        this.gateLevelLabel.string = 'Lv.' + this.gateLevel + ""

        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
        this.gameGenerateFruit();
        this.CurrCompoundNum = 0;
        this.isPause=false;

        //背景水果滚动
        tween(this.fruitBg0)
        .by(13,{angle:360})
        .repeatForever()
        .start()

        tween(this.fruitBg1)
        .by(13,{angle:360})
        .repeatForever()
        .start()

        tween(this.fruitBg2)
        .by(13,{angle:360})
        .repeatForever()
        .start()

    }


    onclickShareBtn(){
        this.clickMusic();
        console.log('share')
        let wx=window["wx"]||window["tt"]
        //@ts-ignore
        wx.shareAppMessage(function () { 
            return {
                title: '你有玩过这款超好玩的翡翠合成游戏吗?',
                imageUrl: '',
            }
        })
    }

    clickMusic(){
        AudioMgr.ins.playOneShot("audio/clickBtn", 0.8);
    }

    onTouchStart(event: EventTouch) {
        if (this.isPowerHammerIng==true) {
            this.createTipNode("请先点击要消灭的翡翠")
            return;
        }
        if (this.isCanTouch==false) {
            return;
        }

        let touchWorldPos=event.getUILocation();

        let touchPos=this.fruitRoot.getComponent(UITransform).convertToNodeSpaceAR(v3(touchWorldPos.x,touchWorldPos.y,0))

        if (this.existFruit&&this.existFruit.isValid) {
            this.existFruit.setPosition(touchPos.x,500,0)
        }
    }

    onTouchMove(event: EventTouch) {
        if (this.isPowerHammerIng==true||this.isCanTouch==false) {
            return;
        }
        let delta = event.getUIDelta();
        if (this.existFruit&&this.existFruit.isValid) {
            // if (Math.abs(this.existFruit.position.x) <= 375) {
                this.existFruit.setPosition(this.existFruit.position.x + delta.x, this.existFruit.position.y, 0)
            // }
            if (Math.abs(this.existFruit.position.x)> 375) {
                if (this.existFruit.position.x<0) {
                    this.existFruit.setPosition(-375,this.existFruit.position.y)
                }
                else{
                    this.existFruit.setPosition(375,this.existFruit.position.y)
                }
            }
        }
    }

    onTouchEnd() {
        if (this.isPowerHammerIng==true||this.isCanTouch==false) {
            return;
        }
        if (this.existFruit) {
            this.isCommonBallIng=false;
            if (this.existFruit&&this.existFruit.isValid) {
                Tween.stopAllByTag(26)
            this.existFruit.getComponent(RigidBody2D).type = ERigidBody2DType.Dynamic
            }
            this.existFruit=null;

            setTimeout(() => {
                this.gameGenerateFruit();
            }, 1500)
        }
       
    }

    tempCount=0;
    saveDataTempCount=-3;
    update(deltaTime: number) {
        if (this.isNeedCompound!=-1) {
            this.compoundGenerateFruit(this.isNeedCompound,this.isNeedCompoundPos);
            this.isNeedCompound=-1;
        }

        // if (this.isPause==false) {
        //     this.tempCount+=deltaTime;
        //     if (this.tempCount>3) {
        //         this.tempCount=0;
        //         this.judgeIsBeAboutToGameOverAndDisplay();
        //     }
        // }

        this.saveDataTempCount+=deltaTime;
        if (this.saveDataTempCount>2) {
            this.saveDataTempCount=0;
            let dic=new Dictionary<number,number[]>();

            for (let i = 0; i < this.fruitRoot.children.length; i++) {
                if (this.fruitRoot.children[i].getComponent(Fruit).IsFallRound == true && this.fruitRoot.children[i].getComponent(Fruit).isDie == false) {
                    dic.set(i,[this.fruitRoot.children[i].position.x,this.fruitRoot.children[i].position.y,this.fruitRoot.children[i].angle,this.fruitRoot.children[i].getComponent(Fruit).fruitType])
                    // localStorage.setItem("dic",JSON.stringify(dic));
                    // console.log(JSON.parse(localStorage.getItem("dic")))
                    // console.log(JSON.parse(localStorage.getItem("dic"))._typeValueList[0])
                }
            }

            localStorage.setItem("fruitsData",JSON.stringify(dic));
           
        }
       
    }

    //创建水果
    createfruit(_fruitType,createPos) {
        resources.load(`prefab/fruits/fruit${_fruitType}`, Prefab, (err, res) => {
            let pre = instantiate(res);
            pre.setParent(this.fruitRoot);
            pre.setPosition(createPos.x, createPos.y, 0);
            pre.getComponent(Fruit).init(_fruitType);

            this.existFruit = pre;
            tween(this.existFruit)
            .by(1.5,{angle:360})
            .tag(26)
            .repeatForever()
            .start()
            this.judgeIsGameOver();
            this.judgeIsBeAboutToGameOverAndDisplay();
        })
    }

    //游戏生成水果
    gameGenerateFruit(){
        // let randCount=randomNum(1,100);
        // let fruitType=0;

        // if (1<=randCount&&randCount<30) {//30%
        //     fruitType=0;
        // }
        // else if(30<=randCount&&randCount<55){//25%
        //     fruitType=1;
        // }
        // else if(55<=randCount&&randCount<75){//20%
        //     fruitType=2;
        // }
        // else if(75<=randCount&&randCount<90){//15%
        //     fruitType=3;
        // }
        // else if(90<=randCount&&randCount<=100){//10%
        //     fruitType=4;
        // }

        // this.createfruit(fruitType,v2(0,500));

        let fruitMaxType=2;
        let fruitType=0;
        if (this.CurrCompoundNum<=3) {//1,2,3
            fruitMaxType=2
        }
        else if(3<this.CurrCompoundNum&&this.CurrCompoundNum<=5){//4,5
            fruitMaxType=4
        }
        else{
            fruitMaxType=5
        }
        fruitType=randomNum(0,fruitMaxType);
        this.createfruit(fruitType,v2(0,500));
        // this.createfruit(randomNum(11,13),v2(0,500));

    }

    //合成生成水果
    compoundGenerateFruit(_fruitType, createPos) {
        AudioMgr.ins.playOneShot("audio/water",0.8);
        if(sys.platform==sys.Platform.WECHAT_GAME || sys.platform==sys.Platform.BYTEDANCE_MINI_GAME){
            var wx = window['tt']||window['wx']
            if(this.isZhenDong){
                wx.vibrateLong({
                    success: function (res) {
                      console.log('短震动成功');
                    },
                    fail: function (err) {
                      console.log('短震动失败', err);
                    }
                  });
            }
        }
        resources.load(`prefab/fruits/fruit${_fruitType}`, Prefab, (err, res) => {
            let pre = instantiate(res);
            pre.setScale(0.4, 0.4, 1);
            pre.setParent(this.fruitRoot);
            pre.setPosition(createPos.x, createPos.y, 0);
            pre.getComponent(RigidBody2D).type = ERigidBody2DType.Dynamic;
            
            pre.getChildByName("bombParticle2D").getComponent(ParticleSystem2D).resetSystem();
            pre.getComponent(Fruit).isAreadlyLoudAudio=true;
            pre.getComponent(Fruit).init(_fruitType);


            this.GameScore += _fruitType;
            this.CurrCompoundNum += 1;

            tween(pre)
                .to(0.1, { scale: v3(1, 1, 1) })
                .start();

            if (_fruitType >= this.maxFruit) {//判断是否游戏胜利
                this.gameWin();
            }
        })
    }

    gameWin() {
        Adsdk.instance.showInterstitialAd()
        this.winPanel.active = true;
        this.isPause=true;
        // this.winPanel.getChildByName("light").angle=0;
        // tween(this.winPanel.getChildByName("light"))
        // .tag(11)
        // .by(3,{angle:360})
        // .repeatForever()
        // .start()
        this.winPanel.getChildByName("currLevelLabel").getComponent(Label).string=this.gateLevel+"";
        this.gateLevel += 1;
        localStorage.setItem("gateLevel", JSON.stringify(this.gateLevel));

        // this.gameWinToSeeAdvGetPropType=randomNum(0,1);
        // this.winPanel.getChildByName("propSp").getComponent(Sprite).spriteFrame=this.propImg[this.gameWinToSeeAdvGetPropType];
        this.isCanTouch=false;

    }



    onclickSeeAdvGetGroundPropBtn() {
        this.clickMusic();
        Adsdk.instance.showVideo(() => {
            this.HasGroundVibrationPropNum += 1;
            this.createTipNode("成功获得震动道具x1")
            this.onclickWinPanelComfireBtn();
                }, () => {

            })
    }
    onclickSeeAdvGetPowerHammerPropBtn(){
        this.clickMusic();
        Adsdk.instance.showVideo(()=>{
            this.HasPowerHammerNum+=1;
            this.createTipNode("成功获得消除道具x1");
            this.onclickWinPanelComfireBtn();
                },()=>{
                    
        })
    }

    onclickWinPanelComfireBtn() {
        this.reInit();
    }

    reInit(){
        // Tween.stopAll();
        setTimeout(() => {
            this.isCanTouch=true;
            Adsdk.instance.hideGridAdLeftOne()
            Adsdk.instance.hideGridAdRightOne()
            Adsdk.instance.showGridAdLeftOne()
            Adsdk.instance.showGridAdRightOne()
        }, 500);
        this.dieLineRoot.active=false;
        // this.existFruit = null;
        this.isNeedCompound = -1;
        this.isNeedCompoundPos = null;
        this.failPanel.active = false;
        this.winPanel.active = false;
        this.settingPanel.active = false;
        this.isPause=false;
        this.GameScore = this.gameScore;
        // this.fruitRoot.removeAllChildren();
        this.gateLevelLabel.string = 'Lv.' +  this.gateLevel + ""
        this.CurrCompoundNum=0;
        this.isPowerHammerIng=false;
        this.isCommonBallIng=false;

        // setTimeout(() => {
        //     this.gameGenerateFruit();
        // }, 500);
    }


    //关闭设置面板
    onclicksettingPanelCloseBtn(){
        this.clickMusic();
        this.settingPanel.active = false
        setTimeout(() => {
            this.isCanTouch=true;
        }, 500);

    }
    //打开设置面板
    onclicksettingPanelBtn() {
        this.clickMusic();
        Adsdk.instance.showInterstitialAd()
        this.isCanTouch = false
        this.settingPanel.active = true
    }


    onclickfailPanelRestartBtn() {
        this.clickMusic();
        this.gateLevel = 1
        localStorage.setItem("gateLevel", JSON.stringify(this.gateLevel));
        this.existFruit = null;
        this.fruitRoot.removeAllChildren();
        this.reInit();
          setTimeout(() => {
            this.gameGenerateFruit();
        }, 500);
    }

    onclickCommonBallPropBtn() {
        this.clickMusic();
        if (this.isCommonBallIng) {
            this.createTipNode("正在使用万能球");
            return;
        }
        if(this.isPowerHammerIng){
            this.createTipNode("正在使用消除道具");
            return;
        }
        if (!this.existFruit) {
            return;
        }
        if (this.fruitRoot.children.length<=1) {
            this.createTipNode("无需使用道具");
            return;
        }
        if (this.HasCommonBallNum > 0) {
            this.HasCommonBallNum -= 1;

            this.useCommonBallProp();
        }
        else {
            Adsdk.instance.showVideo(()=>{
                this.useCommonBallProp();
            },()=>{

            })
        }
    }

    useCommonBallProp(){
        this.isCommonBallIng=true;

        if(this.existFruit){
            this.existFruit.destroy();
            this.existFruit=null;

            resources.load(`prefab/commonBall`, Prefab, (err, res) => {
                let pre = instantiate(res);
                pre.setParent(this.fruitRoot);
                pre.setPosition(0, 500, 0);
                this.existFruit = pre;
            })

        }
    }

    onclickPowerHammerPropBtn() {
        this.clickMusic();
        if (this.isPowerHammerIng) {
            this.createTipNode("正在使用消除道具");
            return;
        }
        if (this.isCommonBallIng) {
            this.createTipNode("正在使用万能球");
            return;
        }
        if (this.fruitRoot.children.length<=1) {
            this.createTipNode("无需使用道具");
            return;
        }
        if (this.HasPowerHammerNum > 0) {
            this.HasPowerHammerNum -= 1;

            this.usePowerHammerProp();
        }
        else {
            Adsdk.instance.showVideo(()=>{
                this.usePowerHammerProp();
            },()=>{

            })
        }
    }

    usePowerHammerProp(){
        this.hammerTipStr.active=true;
        this.isPowerHammerIng=true;
        for (let i = 0; i < this.fruitRoot.children.length; i++) {
            if (this.fruitRoot.children[i]==this.existFruit) {
                continue;
            }
            if (this.fruitRoot.children[i].getChildByName("hammerSp")) {
            this.fruitRoot.children[i].getChildByName("hammerSp").active=true;
            }
        }
        
    }

    onclickGroundVibrationPropBtn() {
        this.clickMusic();
        if (this.isGroundVibrationIng) {
            this.createTipNode("正在使用震动");
            return;
        }
        if (this.fruitRoot.children.length<=1) {
            this.createTipNode("无需使用道具");
            return;
        }
        if (this.HasGroundVibrationPropNum > 0) {
            this.HasGroundVibrationPropNum -= 1;

            this.useGroundVibration();
        }
        else {
            Adsdk.instance.showVideo(()=>{
                this.useGroundVibration();
            },()=>{

            })
        }
    }

    useGroundVibration() {
        this.isGroundVibrationIng = true;
        let prePos = this.ground.getPosition();
        tween(this.ground)
            .by(0.2, { position: v3(0, 100, 0) })
            .by(0.2, { position: v3(0, -100, 0) })
            .by(0.2, { position: v3(0, 100, 0) })
            .by(0.2, { position: v3(0, -100, 0) })

            .by(0.3, { position: v3(0, 100, 0) })
            .by(0.2, { position: v3(0, -100, 0) })

            .to(0.3, { position: prePos })
            .call(() => {
                this.isGroundVibrationIng = false;
            })
            .start();

    }

    judgeIsGameOver() {
        for (let i = 0; i < this.fruitRoot.children.length; i++) {
            if (this.fruitRoot.children[i] == this.existFruit) {
                continue;
            }
            if (this.fruitRoot.children[i].getComponent(Fruit).IsFallRound) {
                if (this.fruitRoot.children[i].position.y > this.dieLineRoot.position.y) {
                    this.gameOver();
                }
            }

        }

    }

    //判断是否游戏即将结束并且展示线
    judgeIsBeAboutToGameOverAndDisplay(){
        let res =false;
        for (let i = 0; i < this.fruitRoot.children.length; i++) {
            if (this.fruitRoot.children[i]==this.existFruit) {
                continue;
            }
            if (this.fruitRoot.children[i].getComponent(Fruit).IsFallRound) {
                if (this.fruitRoot.children[i].position.y>this.dieLineRoot.position.y-300) {
                    res=true;
                }
            }
          
        }

        if (res) {
            this.dieLineRoot.active = true;
            tween(this.dieLineRoot.getChildByName("dieLine").getComponent(UIOpacity))
                .to(0.2, { opacity: 50 })
                .to(0.2, { opacity: 255 })
                .to(0.2, { opacity: 50 })
                .to(0.2, { opacity: 255 })
                .call(() => {
                    this.dieLineRoot.active = false;
                })
                .start()
    
        }

    }

    gameOver() {
        this.isCanTouch=false;
        this.isPause=true;
        this.dieLineRoot.active = true;
        this.canvasMask.active = true;
        tween(this.dieLineRoot.getChildByName("dieLine").getComponent(UIOpacity))
            .to(0.3, { opacity: 50 })
            .to(0.3, { opacity: 255 })
            .to(0.3, { opacity: 50 })
            .to(0.3, { opacity: 255 })
            .call(() => {
                
                this.failPanel.getChildByName("scoreLabel").getComponent(Label).string = this.gameScore+"";
                this.failPanel.active = true;
                this.canvasMask.active = false;
                Adsdk.instance.showInterstitialAd()

            })
            .start()

    }

    createTipNode(str) {
        let pre = instantiate(this.tipNodePre);
        pre.getChildByName("Label").getComponent(Label).string=str;
        pre.setParent(this.tipRoot);
        pre.setPosition(0, -100, 0);
        tween(pre)
            .to(0.8, { position: v3(0, 300, 0) })
            .call(() => {
                pre.destroy();
            })
            .start();
    }


    //设置音效震动
    setYxZd(){
        if(this.isYinXiao){
            this.yinxiaoBtn.getChildByName('off').active = false
        }else{
            this.yinxiaoBtn.getChildByName('off').active = true
        }
        if(this.isYinYue){
            this.yinyueBtn.getChildByName('off').active = false
        }else{
            this.yinyueBtn.getChildByName('off').active = true
        }
        if(this.isZhenDong){
            this.zhendongBtn.getChildByName('off').active = false
        }else{
            this.zhendongBtn.getChildByName('off').active = true
        }
    }

    onclickYinXiaoBtn(){
        this.clickMusic();
        this.isYinXiao = !this.isYinXiao
        localStorage.setItem("isYinXiao",JSON.stringify(this.isYinXiao));
        this.setYxZd()
    }

    onclickYinYueBtn(){
        this.clickMusic();
        this.isYinYue = !this.isYinYue
        if(this.isYinYue){
            AudioMgr.ins.play("audio/bgm",1);
        }else{
            AudioMgr.ins.stop();
        }
        localStorage.setItem("isYinYue",JSON.stringify(this.isYinYue));
        this.setYxZd()
    }

    onclickZhenDongBtn(){
        this.clickMusic();
        this.isZhenDong = !this.isZhenDong
        localStorage.setItem("isZhenDong",JSON.stringify(this.isZhenDong));
        this.setYxZd()
    }

    //点击复活按钮
    onclickReviveBtn() {
        this.clickMusic();
        Adsdk.instance.showVideo(()=>{
            setTimeout(() => {
                this.isCanTouch = true;
    
            }, 500);
            this.isPause = false;
            this.dieLineRoot.active = false;
            this.failPanel.active = false;
    
            for (let i = 0; i < this.fruitRoot.children.length; i++) {
                if (this.fruitRoot.children[i].position.y < -190) {
                    this.fruitRoot.children[i].getComponent(Fruit).die();
                }
    
            }
        },()=>{

        })
    }

}


